//
// Created by sgyt on 2020/4/10.
// linux 屏障
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

//屏障
pthread_barrier_t barrier;

//屏障总数
#define MAX_BARRIER 4

void *thread_fun(void *arg);

int main(int argc,char *argv[])
{
    pthread_t pthread1,pthread2,pthread3,pthread4;

    //初始化屏障
    pthread_barrier_init(&barrier,NULL,MAX_BARRIER);

    //开始
    if((pthread_create(&pthread1,NULL,thread_fun,"1")) != 0)
    {
        perror("pthread_create is error\n");
        exit(EXIT_FAILURE);
    }

    if((pthread_create(&pthread2,NULL,thread_fun,"2")) != 0)
    {
        perror("pthread_create is error\n");
        exit(EXIT_FAILURE);
    }

    if((pthread_create(&pthread3,NULL,thread_fun,"3")) != 0)
    {
        perror("pthread_create is error\n");
        exit(EXIT_FAILURE);
    }

    //等待工作完成
    pthread_barrier_wait(&barrier);
    printf("所有线程工作已完成。。。\n");

    sleep(1);
    return 0;
}


void *thread_fun(void *arg)
{
    int res;
    char *buf = (char *)arg;
    printf("线程%s工作完成。。。\n",buf);

    //屏障等待
    res = pthread_barrier_wait(&barrier);

    if(res == PTHREAD_BARRIER_SERIAL_THREAD)
    {
        printf("线程%s，wait后第一个返回\n",buf);
        fflush(stdout);
    }else if(res == 0)
    {
        printf("线程%s,wait后返回为0\n",buf);
        fflush(stdout);
    }else{
        perror("pthread_barrier_wait is error\n");
        exit(EXIT_FAILURE);
    }

    return NULL;
}

